import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
export default function index() {
  const mountRef = useRef(null);

  useEffect(() => {
    const scene = new THREE.Scene();

    const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
    const boxMeterial = new THREE.MeshBasicMaterial({ color: 0xffff00 });
    const boxMesh = new THREE.Mesh(boxGeometry, boxMeterial);
    scene.add(boxMesh);
    // 相机
    // 正交相机--平行渲染
    // const camera = new THREE.OrthographicCamera(-1, -1, 2, 1, 0, 1000);
    // 透视相机 THREE.PerspectiveCamera(视野视角，宽高比，近距，远距)
    const camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth / window.innerHeight,
      1,
      1000
    );
    camera.lookAt(boxMesh.position); // 看向物体
    camera.position.z = 5;
    scene.add(camera);

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    mountRef.current.appendChild(renderer.domElement);

    // 轨道控制器
    const controls = new OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
    // 动画
    const clock = new THREE.Clock();
    const animation = () => {
      const detal = clock.getDelta();
      controls.update(); // 更新控制器
      renderer.render(scene, camera);
      window.requestAnimationFrame(animation); // 会在下一帧调用此函数
    };
    animation();
  }, []);

  return (
    <div
      ref={mountRef}
      style={{ width: '100%', height: '100vh' }}
    />
  );
}
